package com.ai.notices.service.impl;

import com.ai.notices.common.constants.Constants;
import com.ai.notices.common.util.BeanUtil;
import com.ai.notices.common.util.ObjectCopyUtil;
import com.ai.notices.common.util.PagedResult;
import com.ai.notices.common.util.StringUtil;
import com.ai.notices.dao.mysql.mapper.GdsInfoImpMapper;
import com.ai.notices.dao.mysql.mapper.GdsInfoMapper;
import com.ai.notices.dao.mysql.mapper.GdsPicMapper;
import com.ai.notices.dao.mysql.model.*;
import com.ai.notices.service.interfaces.IGdsInfoSV;
import com.ai.notices.service.resp.GdsInfoResp;
import com.ai.notices.service.resp.GdsPicResp;
import com.ai.notices.utils.mongo.FileManagerSVC;
import com.ai.notices.utils.mongo.ImangeServer;
import com.ai.notices.web.controller.vo.GdsInfoVO;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by huangzh on 17/6/17.
 */
@Service
public class GdsInfoSVIpml implements IGdsInfoSV {

    @Autowired
    private GdsInfoMapper gdsInfoMapper;

    @Autowired
    private GdsInfoImpMapper gdsInfoImpMapper;
    @Autowired
    private GdsPicMapper gdsPicMapper;
    @Autowired
	private FileManagerSVC FileUtil;
    @Override
    public PagedResult<GdsInfo> queryGdsInfoByPage(GdsInfoVO gdsInfo, Integer pageNo, Integer pageSize)throws Exception{
        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? 50 : pageSize;
        PageHelper.startPage(pageNo, pageSize); // startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
        GdsInfoExample example = new GdsInfoExample();
        GdsInfoExample.Criteria cri = example.createCriteria();
        if (!StringUtils.isEmpty(gdsInfo.getBatchId())) {
            cri.andBatchIdEqualTo(gdsInfo.getBatchId());
        }
        if (null != gdsInfo.getGdsId()) {
            cri.andGdsIdEqualTo(gdsInfo.getGdsId());
        }
        if (!StringUtils.isEmpty(gdsInfo.getGdsCode())) {
            cri.andGdsCodeEqualTo(gdsInfo.getGdsCode());
        }
        if (!StringUtils.isEmpty(gdsInfo.getBrand())) {
            cri.andBrandLike("%"+gdsInfo.getBrand()+"%");
        }
        if (!StringUtils.isEmpty(gdsInfo.getGdsName())) {
            cri.andGdsNameLike("%"+gdsInfo.getGdsName()+"%");
        }
        if (!StringUtils.isEmpty(gdsInfo.getState())) {
            cri.andStateEqualTo(gdsInfo.getState());
        }

        example.setOrderByClause(" id desc");

        return BeanUtil.toPagedResult(gdsInfoMapper.selectByExample(example));
    }

    public int updateGdsInfoById(GdsInfoVO gdsInfoVO)throws Exception{
        GdsInfo gdsInfo = new GdsInfo();
        gdsInfo.setId(gdsInfoVO.getId());
        gdsInfo.setState(gdsInfoVO.getState());
        return gdsInfoMapper.updateByPrimaryKeySelective(gdsInfo);
    }

    @Override
    public void saveGdsInfo(String batchId, AuthStaff authStaff) throws Exception {
        Date date = new Date();
        GdsInfoImpExample example = new GdsInfoImpExample();
        example.createCriteria().andBatchIdEqualTo(batchId);
        List<GdsInfoImp> ordLst = gdsInfoImpMapper.selectByExample(example);
        for (GdsInfoImp imp : ordLst) {
            try{
                GdsInfo gdsInfo = new GdsInfo();
                gdsInfo.setGdsId(imp.getGdsId());
                gdsInfo.setBatchId(batchId);
                gdsInfo.setBarCode(imp.getBarCode());
                gdsInfo.setBrand(imp.getBrand());
                gdsInfo.setCatgs(imp.getCatgs());
                gdsInfo.setGdsCode(imp.getGdsCode());
                gdsInfo.setGdsName(imp.getGdsName());
                gdsInfo.setLegalMeasureUnit(imp.getLegalMeasureUnit());
                if(StringUtil.isNotBlank(imp.getLegalNum())){
                    gdsInfo.setLegalNum(Double.valueOf(imp.getLegalNum()));
                }
                gdsInfo.setMeasureCode(imp.getMeasureCode());
                gdsInfo.setMeasureUnit(imp.getMeasureUnit());
                if(StringUtil.isNotBlank(imp.getPrice())){
                    double num;
                    java.text.DecimalFormat myformat=new java.text.DecimalFormat("#0.00");
                    num=Double.parseDouble(imp.getPrice());//装换为double类型
                    num=Double.parseDouble(myformat.format(num));//保留2为小数
                    gdsInfo.setPrice(((Double)(num*100)).intValue());
                }
                gdsInfo.setProAddress(imp.getProAddress());
                gdsInfo.setRecordCode(imp.getRecordCode());
                gdsInfo.setRemark(imp.getRemark());
                gdsInfo.setSpec(imp.getSpec());
                gdsInfo.setTaxDuty(imp.getTaxDuty());
                gdsInfo.setVender(imp.getVender());
                gdsInfo.setSecMeasureUnit(imp.getSecMeasureUnit());
                gdsInfo.setCreateStaff(authStaff.getStaffCode());
                gdsInfo.setCreateTime(date);
                gdsInfo.setState("1");
                gdsInfoMapper.insert(gdsInfo);
            }catch(Exception e){
                //正式导入出现异常，则将错误信息回写到导入临时表
                GdsInfoImp gdsInfoImp = new GdsInfoImp();
                gdsInfoImp.setGdsId(imp.getGdsId());
                gdsInfoImp.setState("0");
                String errMsg = e.toString();
                if(errMsg.length() > 1024){
                    errMsg = errMsg.substring(0,1023);
                }
                gdsInfoImp.setErrDesc(errMsg);
                gdsInfoImpMapper.updateByPrimaryKeySelective(gdsInfoImp);
            }
        }
    }

    @Override
    public void saveGdsInfoImp(List<Map<String, String>> gdsInfoLst, String batchId, AuthStaff authStaff) throws Exception {
        Date date = new Date();
        for (Map<String, String> map : gdsInfoLst) {
            GdsInfoImp imp = new GdsInfoImp();
            imp.setBatchId(batchId);
            imp.setGdsName(map.get("0"));
            imp.setSpec(map.get("1"));
            imp.setCatgs(map.get("2"));
            imp.setMeasureUnit(map.get("3"));
            imp.setMeasureCode(map.get("4"));
            imp.setTaxDuty(map.get("5"));
            imp.setPrice(map.get("6"));
            imp.setLegalNum(map.get("7"));
            imp.setGdsCode(map.get("8"));
            imp.setLegalMeasureUnit(map.get("9"));
            imp.setSecMeasureUnit(map.get("10"));
            imp.setRecordCode(map.get("11"));
            imp.setBrand(map.get("12"));
            imp.setProAddress(map.get("13"));
            imp.setVender(map.get("14"));
            imp.setBarCode(map.get("15"));
            imp.setRemark(map.get("16"));
            imp.setCreateStaff(authStaff.getStaffCode());
            imp.setCreateTime(date);
            imp.setState("1");
            gdsInfoImpMapper.insert(imp);
        }
    }

    @Override
    public PagedResult<GdsInfoImp> queryGdsInfoImpByPage(GdsInfoImp imp, Integer pageNo, Integer pageSize) throws Exception {
        // TODO Auto-generated method stub
        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? 50 : pageSize;
        PageHelper.startPage(pageNo, pageSize); // startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
        GdsInfoImpExample example = new GdsInfoImpExample();
        GdsInfoImpExample.Criteria criteria = example.createCriteria();
        criteria.andBatchIdEqualTo(imp.getBatchId());
        if (org.apache.commons.lang.StringUtils.isNotBlank(imp.getState())) {
            criteria.andStateEqualTo(imp.getState());
        }
        return BeanUtil.toPagedResult(gdsInfoImpMapper.selectByExample(example));
    }

    @Override
    public List<GdsInfo> queryGdsInfos(GdsInfo gdsInfo)throws Exception{
        GdsInfoExample example = new GdsInfoExample();
        GdsInfoExample.Criteria cri = example.createCriteria();
        if (!StringUtils.isEmpty(gdsInfo.getBatchId())) {
            cri.andBatchIdEqualTo(gdsInfo.getBatchId());
        }
        if (null != gdsInfo.getGdsId()) {
            cri.andGdsIdEqualTo(gdsInfo.getGdsId());
        }
        if (!StringUtils.isEmpty(gdsInfo.getGdsCode())) {
            cri.andGdsCodeEqualTo(gdsInfo.getGdsCode());
        }
        if (!StringUtils.isEmpty(gdsInfo.getBrand())) {
            cri.andBrandLike("%"+gdsInfo.getBrand()+"%");
        }
        if (!StringUtils.isEmpty(gdsInfo.getGdsName())) {
            cri.andGdsNameEqualTo("%"+gdsInfo.getGdsName()+"%");
        }
        if (!StringUtils.isEmpty(gdsInfo.getState())) {
            cri.andStateEqualTo(gdsInfo.getState());
        }

        return gdsInfoMapper.selectByExample(example);
    }

	@Override
	public GdsInfoResp queryGdsInfosByPk(Long pk) throws Exception {
		// TODO Auto-generated method stub
		GdsInfo info = gdsInfoMapper.selectByPrimaryKey(pk);
		GdsInfoResp resp = new GdsInfoResp();
		ObjectCopyUtil.copyObjValue(info, resp, null, false);
		if(!StringUtils.isEmpty(resp.getContentId())){
			resp.setContentUrl(ImangeServer.imageUrl+"/static/html/"+resp.getContentId());
		}
		GdsPicExample example = new GdsPicExample();
		GdsPicExample.Criteria cri = example.createCriteria();
		cri.andGdsIdEqualTo(resp.getId());
		 List<GdsPic> listPic = gdsPicMapper.selectByExample(example);
		 List<GdsPicResp> listPicResp = new ArrayList<>();
		 for(GdsPic pic :listPic){
			 GdsPicResp picResp =  new GdsPicResp();
			 picResp.setPicId(pic.getPicId());
			 picResp.setPicUrl(getImageUrl(pic.getPicId()));
			 listPicResp.add(picResp);
		 }
		 resp.setPicLit(listPicResp);
		return resp;
	}

	@Override
	public GdsInfoResp queryGdsInfosByGdsId(Long gdsId) throws Exception {
		// TODO Auto-generated method stub
		try {
			GdsInfoExample example = new GdsInfoExample();
			example.createCriteria().andGdsIdEqualTo(gdsId);
			List<GdsInfo> gdsInfoLst = gdsInfoMapper.selectByExample(example);
			return queryGdsInfosByPk(gdsInfoLst.get(0).getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new GdsInfoResp();
	}

	@Override
	public void updateGdsInfo(GdsInfoVO vo) throws Exception {
		// TODO Auto-generated method stub
		GdsInfoExample example = new GdsInfoExample();
        GdsInfoExample.Criteria cri = example.createCriteria();
        cri.andIdEqualTo(vo.getId());
        GdsInfo info = new GdsInfo();
        ObjectCopyUtil.copyObjValue(vo, info, null, false);
		gdsInfoMapper.updateByExampleSelective(info, example);
		//解释图片入库
		String images = vo.getImage();
		if(!StringUtils.isEmpty(images)){
			String[] image = images.split(",");
			for(String s : image){
				GdsPic pic = new GdsPic();
				pic.setGdsId(vo.getId());
				pic.setPicId(s);
				pic.setState("1");
				gdsPicMapper.insert(pic);
			}
			
		}
		
	}
	
	@Override
	public void deleGdsPic(GdsInfoVO vo) throws Exception {
		// TODO Auto-generated method stub
		GdsPicExample example = new GdsPicExample();
		GdsPicExample.Criteria cri = example.createCriteria();
		cri.andPicIdEqualTo(vo.getImage());
		gdsPicMapper.deleteByExample(example);
		FileUtil.deleteFile(vo.getImage());
	}

	private String getImageUrl(String imageId) {

		StringBuffer strBuf = new StringBuffer();
		if (!StringUtils.isEmpty(imageId)) {
			String picType = FileUtil.getFileType(imageId);
			if (!StringUtils.isEmpty(picType) && picType.startsWith(".")) {
				strBuf.append(imageId).append(picType);
			} else if (!StringUtils.isEmpty(picType) && !picType.startsWith(".")) {
				strBuf.append(imageId).append(".").append(picType);
			} else {
				strBuf.append(imageId).append(".jpg");
			}

		}

	return ImangeServer.imageUrl+ "/image/" + strBuf.toString() ;
    
    }

    public void updateGdsInfo(List<String> idLst)throws Exception{
        for (String id : idLst) {
            GdsInfo gdsInfo = new GdsInfo();
            gdsInfo.setId(Long.valueOf(id));
            gdsInfo.setState(Constants.STATUS_INVALID);
            gdsInfoMapper.updateByPrimaryKeySelective(gdsInfo);
        }
    }
}
